{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 二分查找"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 概述\n",
    "Input: 有序的列表\n",
    "\n",
    "Output: 存在：返回位置；不存在：返回null\n",
    "\n",
    "注意：\n",
    "- 使用二分查找时，每次都排除一半的数字\n",
    "- 使用二分查找最多需要log2(n)步；简单查找最多需要n步\n",
    "- 大O表示法让我们可以比较操作数，它指出了算法运行时间的增速\n",
    "- 大O表示法给出了最糟糕情况下的运行时间\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 代码实现\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1. Python: Iterative"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-12-27T17:15:11.390697Z",
     "start_time": "2018-12-27T17:15:11.383620Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "def binary_search(sorted_list, item):\n",
    "    low = 0\n",
    "    high = len(sorted_list) - 1\n",
    "    while low <= high:\n",
    "        mid = (low + high) // 2\n",
    "        guess = sorted_list[mid]\n",
    "        if guess == item:\n",
    "            return mid\n",
    "        if guess > item:\n",
    "            high = mid - 1\n",
    "        else:\n",
    "            low = mid + 1\n",
    "    return None\n",
    "\n",
    "# test\n",
    "print(binary_search([1, 2, 3, 4, 5], 3))\n",
    "print(binary_search([1, 2, 3, 4, 5], 6))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. Python: Iterative\n",
    "\n",
    "参考[Rosetta](https://rosettacode.org/wiki/Binary_search#C)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-12-27T17:15:11.678721Z",
     "start_time": "2018-12-27T17:15:11.669605Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "def binary_search_r(sorted_list, item, low=0, high=-1):\n",
    "    if not sorted_list:\n",
    "        return None\n",
    "    # base\n",
    "    \n",
    "    if high==-1:\n",
    "        high = len(sorted_list)-1\n",
    "    if low >= high:\n",
    "        if item == sorted_list[low]:\n",
    "            return low\n",
    "        else:\n",
    "            return None\n",
    "    mid = (low + high) // 2\n",
    "    if sorted_list[mid] > item:\n",
    "        return binary_search_r(sorted_list, item, low, high=mid-1)\n",
    "    if sorted_list[mid] < item:\n",
    "        return binary_search_r(sorted_list, item, low=mid+1, high=high)\n",
    "    else:  # sorted_list[mid] == item\n",
    "        return mid\n",
    "    \n",
    "# test\n",
    "print(binary_search_r([1, 2, 3, 4, 5], 3))\n",
    "print(binary_search_r([1, 2, 3, 4, 5], 6))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3. Python: Library\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-12-27T17:15:12.237908Z",
     "start_time": "2018-12-27T17:15:12.233796Z"
    }
   },
   "outputs": [],
   "source": [
    "import bisect\n",
    "sorted_list = [1, 2, 3, 4, 5]\n",
    "item = 2\n",
    "index = bisect.bisect_left(sorted_list, item) # leftmost insertion point\n",
    "index = bisect.bisect_right(sorted_list, item) # rightmost insertion point\n",
    "index = bisect.bisect(sorted_list, item) # same as bisect_right\n",
    " \n",
    "# same as above but actually insert the item into the list at the given place:\n",
    "bisect.insort_left(sorted_list, item)\n",
    "bisect.insort_right(sorted_list, item)\n",
    "bisect.insort(sorted_list, item)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4. Python: Approximately"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-12-27T17:15:12.535736Z",
     "start_time": "2018-12-27T17:15:12.527169Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "def binary_search_appr(l, value):\n",
    "    low = 0\n",
    "    high = len(l)-1\n",
    "    while low + 1 < high:\n",
    "        mid = (low+high)//2\n",
    "        if l[mid] > value:\n",
    "            high = mid\n",
    "        elif l[mid] < value:\n",
    "            low = mid\n",
    "        else:\n",
    "            return mid\n",
    "    return high if abs(l[high] - value) < abs(l[low] - value) else low\n",
    "\n",
    "print(binary_search_appr([1, 2, 3, 4, 5], 3))\n",
    "print(binary_search_appr([1, 2, 3, 4, 5], 6))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python语法疑问\n",
    ">`is` 与 `==`区别？\n",
    "\n",
    "参考Fluent Python[p223]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  },
  "toc": {
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
